'''
Created on Apr 6, 2012

@author: nathando
'''
import urllib
import json

from entity.entity import Event
from entity.entity import Post
from base import BaseHandler
from web import urls
from web import util
from web import base
from google.appengine.ext import ndb
from app.query import post_async

class EventHandler(BaseHandler):
    """
    Show all details belong to home page
    """
    @base.user_data_print
    @ndb.synctasklet
    def get(self):
        # Query event list
        event_list = yield Event.query().fetch_async(limit=9)
        event_list_dict = []
        for event in event_list:
            # Query post list
            post_list = yield post_async.get_by_event(event.key, limit=2)
            post_list = util.ndb_to_list(post_list)
            event = util.ndb_to_dict(event)
            event["postList"] = post_list
            # Add to dict 
            event_list_dict.append(event)
        # Print event list
        template = util.jinja_environment().get_template('home.html')
        template_values = {'eventDataJson':  json.dumps(event_list_dict) }
        
        # Add extra user information if available
        template_values = util.add_user_data(self,template_values)
        
        self.response.out.write(template.render(template_values))
        

app = urls.app

def main():
    app.run()

if __name__ == '__main__':
    main()
